<?php

namespace app\services;

use app\traits\Page;
use plugin\admin\app\model\Activity;
use plugin\admin\app\model\Exchange;
use plugin\admin\app\model\Goods;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserHistory;
use plugin\admin\app\model\UserProfile;
use plugin\admin\app\model\Video;

class UserHistoryService
{
    public static function add($type, $id, callable $callback = null)
    {
        if (! self::has($type, $id)) {
            UserHistory::insert([
                'user_id' => get_user_id(),
                'thirdparty_id' => $id,
                'type' => $type,
                'created_time' => date('Y-m-d H:i:s'),
            ]);

            if (!is_null($callback)) {
                $callback($type, $id);
            }
        }
    }

    public static function list($page, $length, $type)
    {
        $offset = ($page - 1) * $length;
        $query = UserHistory::where('user_id', get_user_id())->where('type', $type);

        $count = (clone $query)->count();
        $list = $query->offset($offset)->limit($length)->orderByDesc('created_time')->get()->toArray();

        $thirdPartyIds = array_column($list, 'thirdparty_id');

        if ($type == UserHistory::VIDEO) {
            $list = Video::select(['id', 'desc', 'thumb', 'user_id'])->whereIn('id', $thirdPartyIds)->get()->toArray();

            $userIds = array_column($list, 'user_id');
            $users = UserProfile::select(['user_id', 'nickname'])->whereIn('user_id', $userIds)->get()->toArray();
            $users = array_combine(
                array_column($users, 'user_id'),
                array_values($users)
            );

            foreach ($list as $key=>$item) {
                $item['thumb'] = full_url($item['thumb']);
                $item['user_info'] = $users[$item['user_id']];

                $list[$key] = $item;
            }
        }

        return Page::wrap($count, $page, $length, $list);

    }

    public static function count($type)
    {
        return UserHistory::where('type', $type)->count();
    }

    public static function drop($type, $id, callable $callback = null)
    {
        if (is_array($id)) {
            UserHistory::whereIn('thirdparty_id', $id)->where('type', $type)->where('user_id', get_user_id())->delete();
        } else {
            UserHistory::where('thirdparty_id', $id)->where('type', $type)->where('user_id', get_user_id())->delete();
        }
        if (!is_null($callback)) {
            $callback($type, $id);
        }
    }

    public static function clear($type)
    {
        UserHistory::where('user_id', get_user_id())->where('type', $type)->delete();
    }

    public static function has($type, $id)
    {
        return UserHistory::where('thirdparty_id', $id)->where('type', $type)->where('user_id', get_user_id())->count() > 0;
    }
}